import React, { useRef, useState, useEffect } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  message,
  Modal,
} from 'antd';

import { Link } from 'react-router-dom';
import Channel from 'components/Channel';
import { articleAPI, delArticleByIdAPI } from 'api/article';
import defaultImgSrc from 'assets/error.png';
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

const { confirm } = Modal;
const { RangePicker } = DatePicker;
export default function ArticleList(props) {
  // ref可以用来存储数据
  // 1. 创建ref，准备保存form数据
  const formDataRef = useRef();
  const pageDataRef = useRef({});
  // 请求回来最后一页的数据数量
  const numRef = useRef(10);

  const [articleData, setArticleData] = useState({});
  const articleCurrent = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        return value.images.length > 0 ? (
          <img src={value.images[0]} alt="" width={100} height={60}></img>
        ) : (
          <img src={defaultImgSrc} alt="" width={100} height={60}></img>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        // find返回一个对象
        let current = articleCurrent.find((item) => item.id === value);
        return <Tag color={current.color}>{current.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      // 表格参数传两个字段
      title: '操作',
      key: 'action',
      render: (value, record) => {
        return (
          // Space有间隔
          <Space>
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => props.history.push(`/edit/${record.id}`)}
            />
            <Button
              style={{ color: '#ff4d4f', borderColor: '#ff4d4f' }}
              shape="circle"
              icon={<DeleteOutlined onClick={() => delFn(record.id)} />}
            />
          </Space>
        );
      },
    },
  ];
  // JSON转字符串的时候会丢掉值为underfined的键名
  // 表单提交
  const onFinish = (values) => {
    // 这里复制一份对象
    let formData = { ...values };

    // 处理status为-1
    if (values.status === -1) {
      delete formData.status;
    }
    // 处理日期

    // 2. 如果选了时间范围，转换键名
    // 🔔 不确定格式，要跟后台确定，字段名要与接口一模一样
    if (values.date) {
      // 求一天的数量，解决筛选问题,没有弄上分秒
      const begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
      delete formData.date;
    }
    formDataRef.current = formData;
    getArticleData(formData);
  };
  useEffect(() => {
    getArticleData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // 获取表格数据
  // const getArticleData = async (page, per_page) => {
  //   const res = await articleAPI({ page, per_page });
  const getArticleData = async (params) => {
    const res = await articleAPI(params);
    setArticleData(res.data);
    // console.log(res);
    numRef.current = res.data.results.length;
  };

  //实现分页功能
  // const handlePageChange = (page, perSize) => {
  //   getArticleData(page, perSize);
  const handlePageChange = (page, per_page) => {
    // console.log(numRef.current.length);
    if (numRef.current < 1 && page > 1) {
      page = page--;
    }

    pageDataRef.current = { page, per_page };
    const formData = formDataRef.current || {};
    getArticleData({ page, per_page, ...formData });
  };
  // 删除功能
  const delFn = (id) => {
    // confirm
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除这篇文章吗？',
      onOk: async () => {
        // 二次请求
        await delArticleByIdAPI(id);
        // 刷新时间，记录一下，筛选时得状态
        message.success('删除成功', 1);
        const formData = formDataRef.current || {};
        // const page = pageDataRef.current;

        // 注意带上分页的数据上去
        getArticleData({ ...formData, ...pageDataRef.current });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  return (
    <div style={{ paddingTop: 24 }}>
      {/* 可以在属性中写jsx */}
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          autoComplete="off"
          onFinish={onFinish}
          initialValues={{ status: -1 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 下拉框 */}
          <Form.Item
            label="频道:"
            name="channel_id"
            style={{ width: 220 }}
            placeholder="请选择频道列表"
          >
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="日期:" name="date">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        {/* 表格 */}
        <p>根据筛选条件共查询到2000条数据</p>
        {/* 给表格key值 */}
        <Table
          dataSource={articleData.results}
          columns={columns}
          rowKey="id"
          pagination={{
            onChange: handlePageChange,
            position: ['bottomCenter'],

            current: articleData.page,
            pageSize: articleData.perPage,
            total: articleData.total_count,
          }}
        />
      </Card>
    </div>
  );
}
